package demo.controller;

import demo.common.QueryData;
import demo.common.ResultJson;
import demo.model.Student;
import demo.service.StudentService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;

/**
 * 学生（Student）数据CURD操作控制器
 */
@RestController
@RequestMapping("/student")
public class StudentController {
    /**
     * 业务逻辑层对象，提供数据CURD，级其他功能
     */
    private final StudentService service;

    public StudentController(StudentService service) {
        this.service = service;
    }

    @PostMapping("/query")
    public ResultJson query(@RequestBody QueryData<Student> queryData) {
        Pageable pageable = queryData.buildPageable();
        Page<Student> pages = service.findAll(pageable);
        List<Student> courseList = pages.getContent();
        long total = pages.getTotalElements();
        return ResultJson.ok().data("items", courseList).data("total", total);
    }

    @GetMapping("/{id}")
    public ResultJson getById(@PathVariable Long id) {
        Student student = service.findById(id);
        return ResultJson.ok().data("item", student);
    }

    @PostMapping("")
    public ResultJson add(@Valid @RequestBody Student student) {
        service.add(student);
        return ResultJson.ok().message("添加" + student + "成功");
    }

    @PutMapping("")
    public ResultJson update(@Valid @RequestBody Student student) {
        service.update(student);
        return ResultJson.ok().message("修改" + student + "成功");
    }

    @DeleteMapping("/{id}")
    public ResultJson deleteById(@PathVariable Long id) {
        Student student = service.delete(id);
        return ResultJson.ok().message("删除" + student + "成功");
    }

    @GetMapping("/{id}/photo")
    public ResponseEntity<byte[]> getPhoto(@PathVariable Long id) {
        Student student = service.findById(id);
        if (student.getPhoto() == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        return new ResponseEntity<>(student.getPhoto(), headers, HttpStatus.OK);
    }

    @PostMapping("/{id}/photo")
    public ResultJson setPhoto(@PathVariable Long id, MultipartFile file) {
        service.setPhoto(id, file);
        return ResultJson.ok().message("上传照片成功");
    }


    @GetMapping("/select-data")
    public ResultJson getSelectData() {
        HashMap<String, Object> selectData = service.getSelectData();
        return ResultJson.ok().data(selectData);
    }
}
